package com.dy.yunying.biz.controller.raffle;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dy.yunying.api.entity.hongbao.HbActivityArea;
import com.dy.yunying.api.entity.raffle.RaffleActivity;
import com.dy.yunying.api.enums.SourceTypeEnum;
import com.dy.yunying.api.req.hongbao.GiftCodeReq;
import com.dy.yunying.api.req.raffle.RaffleActivityEditReq;
import com.dy.yunying.api.req.raffle.RaffleActivityReq;
import com.dy.yunying.biz.service.hbdata.HbActivityAreaService;
import com.dy.yunying.biz.service.hongbao.HbGiftBagService;
import com.dy.yunying.biz.service.raffle.RaffleActivityService;
import com.dy.yunying.biz.utils.DateUtils;
import com.pig4cloud.pig.common.core.constant.CommonConstants;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.log.annotation.SysLog;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
 * 抽奖活动配置表服务控制器
 *
 * @author zjz
 * @since 2022-11-07 18:36:03
 * @description 由 zjz 创建
 */
@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/raffleActivity")
public class RaffleActivityController{
    private final RaffleActivityService raffleActivityService;
	private	final HbGiftBagService  hbGiftBagService;
	private final HbActivityAreaService hbActivityAreaService;
	/**
	 * 分页列表
	 * @param record
	 * @return
	 */
	@RequestMapping("/getPage")
	public R getPage(RaffleActivityReq record) {
		return raffleActivityService.getPage(record);
	}

	/**
	 * 列表
	 * @param record
	 * @return
	 */
	@RequestMapping("/getList")
	public R getList(@RequestBody RaffleActivityReq record) {
		return raffleActivityService.getList(record);
	}


	/**
	 * 新增
	 * @param record
	 * @return
	 */
	@RequestMapping("/save")
	@PreAuthorize("@pms.hasPermission('RAFFLE_ACTIVITY_ADD')")
	public R save(@RequestBody RaffleActivityEditReq record) {
		// 验证入参
		R result = checkParams(record);
		if (CommonConstants.FAIL.equals(result.getCode())) {
			return result;
		}
		record.setId(null);
		return raffleActivityService.createEdit(record);
	}

	/**
	 * 编辑
	 * @param record
	 * @return
	 */
	@RequestMapping("/edit")
	@PreAuthorize("@pms.hasPermission('RAFFLE_ACTIVITY_EDIT')")
	public R edit(@RequestBody RaffleActivityEditReq record) {
		if (record.getId() == null) {
			return R.failed("未获取到唯一主键ID");
		}
		RaffleActivity raffleActivity = raffleActivityService.getById(record.getId());
		if(raffleActivity==null){
			return R.failed("活动ID不存在");
		}
		if(raffleActivity.getActivityStatus()!=1){
			List<HbActivityArea> areList = hbActivityAreaService.getBaseMapper().selectList(new QueryWrapper<HbActivityArea>().in("activity_id", record.getId()).eq("source_type", SourceTypeEnum.RAFFLE.getType()).eq("deleted", "0").orderByAsc("area_id"));
			List<Long> areIds = areList.stream().map(HbActivityArea::getAreaId).collect(Collectors.toList());
			Collections.sort(record.getAreaList());
			Collections.sort(areIds);
			if( !(areIds.contains(0L)&&record.getAreaList().contains(0L)) && !areIds.equals(record.getAreaList())){
				return R.failed("上线后区服不能修改，仅支持修改结束时间");
			}
			// 时间验证
			if (StringUtils.isBlank(record.getStartTime()) || StringUtils.isBlank(record.getFinishTime())) {
				return R.failed("开始时间或结束时间不能为空");
			}
			Date startTime = DateUtils.stringToDate(record.getStartTime(), DateUtils.YYYY_MM_DD_HH_MM_SS);
			Date endTime = DateUtils.stringToDate(record.getFinishTime(), DateUtils.YYYY_MM_DD_HH_MM_SS);
			if(startTime.getTime()!=raffleActivity.getStartTime().getTime()){
				return R.failed("上线后仅支持修改结束时间");
			}
			if (startTime.getTime() > endTime.getTime()) {
				return R.failed("开始时间不能大于结束时间");
			}
			if (System.currentTimeMillis() > endTime.getTime()) {
				return R.failed("结束时间不能小于当前时间");
			}
			raffleActivity.setFinishTime(endTime);
			if (StringUtils.isBlank(record.getActivityRule())) {
				return R.failed("请填写活动规则");
			}
			raffleActivity.setActivityRule(record.getActivityRule());
			raffleActivityService.updateById(raffleActivity);
			return R.ok();
		}
		// 验证入参
		R result = checkParams(record);
		if (CommonConstants.FAIL.equals(result.getCode())) {
			return result;
		}
		return raffleActivityService.createEdit(record);
	}


	/**
	 * 复制浮标规则
	 * @return
	 */
	@RequestMapping("/copy")
	@PreAuthorize("@pms.hasPermission('RAFFLE_ACTIVITY_COPY')")
	public R copy(@RequestParam("id") Long id){
		R result = raffleActivityService.copy(id);
		if (CommonConstants.FAIL.equals(result.getCode())) {
			return result;
		}
		return R.ok(0,"浮标规则复制成功");
	}

	/**
	 * 批量更新kv图
	 * @return
	 */
	@RequestMapping("/batchKvpic")
	@SysLog("批量更新kv图")
	@PreAuthorize("@pms.hasPermission('RAFFLE_ACTIVITY_BATCH_KVPIC')")
	public R batchKvpic(@RequestBody RaffleActivityEditReq record){
		if (StringUtils.isBlank(record.getIds())){
			return R.failed("请选择活动");
		}
		if (StringUtils.isBlank(record.getKvpic())){
			return R.failed("请上传KV图");
		}
		return raffleActivityService.batchKvpic(record);
	}
	/**
	 * 更新活动状态
	 * @return
	 */
	@RequestMapping("/activityStatus")
	@SysLog("更新活动状态")
	@PreAuthorize("@pms.hasPermission('RAFFLE_ACTIVITY_STATUS')")
	public R activityStatus(@RequestBody RaffleActivityEditReq record){
		if (Objects.isNull(record.getId())){
			return R.failed("未获取到活动ID");
		}
		if (Objects.isNull(record.getActivityStatus())){
			return R.failed("未获取到活动状态");
		}
		return raffleActivityService.activityStatus(record);
	}

	/**
	 * 新增编辑 - 参数验证
	 * @param record
	 * @return
	 */
	public R checkParams(RaffleActivityEditReq record) {
		// 时间验证
		if (StringUtils.isBlank(record.getStartTime()) || StringUtils.isBlank(record.getFinishTime())) {
			return R.failed("开始时间或结束时间不能为空");
		}
		Date startTime = DateUtils.stringToDate(record.getStartTime(), DateUtils.YYYY_MM_DD_HH_MM_SS);
		Date endTime = DateUtils.stringToDate(record.getFinishTime(), DateUtils.YYYY_MM_DD_HH_MM_SS);
		if (startTime.getTime() > endTime.getTime()) {
			return R.failed("开始时间不能大于结束时间");
		}
		if (StringUtils.isBlank(record.getActivityName())){
			return R.failed("请输入活动名称");
		}
		record.setActivityName(record.getActivityName().trim());
		if(StringUtils.isNotBlank(record.getPointsShow())){
			record.setPointsShow(record.getPointsShow().trim());
		}

		if (System.currentTimeMillis() > endTime.getTime()) {
			return R.failed("结束时间不能小于当前时间");
		}
		// 区服验证
		if (CollectionUtils.isEmpty(record.getAreaList())) {
			return R.failed("请选择区服范围");
		}

		if (record.getParentGameId()==null) {
			return R.failed("请选择主游戏");
		}

		if (record.getActivityMethod()==null) {
			return R.failed("请选择活动方式");
		}

		if (record.getEnableExchange()==null) {
			return R.failed("请选择是否开启兑换功能");
		}
		if(record.getEnableExchange()==1){
			if(record.getPointsQuota() == null){
				return R.failed("请输入抽奖获得积分");
			}
			if(record.getPointsQuota().intValue() <= 0 || record.getPointsQuota().intValue() > 999){
				return R.failed("抽奖获得积分应为1~999");
			}
			if(StringUtils.isBlank(record.getPointsShow())){
				return R.failed("请输入积分展示名称");
			}
		}
		if (record.getExchangeType()==null) {
			return R.failed("请选择兑换类型");
		}

		if (StringUtils.isBlank(record.getActivityRule())) {
			return R.failed("请输入活动规则");
		}

		return R.ok();
	}

	@RequestMapping("/getGiftCodeList")
	public R getGiftCodeList(GiftCodeReq record){
		if (Objects.isNull(record.getType())){
			return R.failed("类型不能为空");
		}
		if (Objects.isNull(record.getObjectId())){
			return R.failed("来源关联ID不能为空");
		}
		return hbGiftBagService.selectGroupCodeLists(record);
	}
}